﻿using Microsoft.AspNetCore.Mvc;
using Model.Other;
using Shop.Interface.Jwt;
using Shop.Interface.User;
using Shop.Models.Dto.Login;
using Shop.Models.Dto.User;
using Shop.WebApi.Config;

namespace Shop.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly ILogger<LoginController> _logger;
        private readonly IUserService userService;
        private ICustomJWTService customJWTService;
        public LoginController(ILogger<LoginController> logger, IUserService userService, ICustomJWTService customJWTService)
        {
            _logger = logger;
            this.userService = userService;
            this.customJWTService = customJWTService;
        }

        [HttpPost]
        public async Task<ApiResult> GetToken([FromBody] LoginReq req)
        {
            //模型验证
            if (ModelState.IsValid)
            {
                UserRes user = await userService.GetUserAsync(req);
                if (user == null)
                {
                    return ResultHelper.Error("账号不存在，用户名或密码错误");
                }
                _logger.LogInformation("登录");
                return ResultHelper.Success(await customJWTService.GetToken(user));
            }
            else
            {
                return ResultHelper.Error("参数错误");
            }
        }
    }
}
